import { defineStore } from 'pinia';
import { TOKEN_NAME } from '@/config/global';
import { store } from '@/store';
import { userInfo, userLogin, userLogout } from '@/api/login';

const InitUserInfo = {
  roles: [],
  name: '',
  account: '',
  avatar: '',
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem(TOKEN_NAME) || 'main_token', // 默认token不走权限
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
    account: (state) => {
      return state.userInfo?.name;
    },
  },
  actions: {
    async login(userInfo: Record<string, unknown>) {
      const res = await userLogin(userInfo);
      console.log('Login successful:', res);
      if (res.code === 20000) {
        this.token = res.data.token;
      } else {
        throw res.message;
      }
    },
    async getUserInfo() {
      const apiRemoteUserInfo = async () => {
        const res = await userInfo();
        if (res.code === 20000) {
          return {
            name: res.data.name,
            account: res.data.account,
            avatar: res.data.avatar,
            roles: ['all'],
          };
        }
        throw res;
      };
      const res = await apiRemoteUserInfo();

      this.userInfo = res;
    },
    async logout() {
      await userLogout(this.token);
      localStorage.removeItem(TOKEN_NAME);
      this.token = '';
      this.userInfo = { ...InitUserInfo };
    },
    async removeToken() {
      this.token = '';
    },
  },
  persist: false,
  // persist: {
  //   afterRestore: (ctx) => {
  //     if (ctx.store.roles && ctx.store.roles.length > 0) {
  //       const permissionStore = usePermissionStore();
  //       console.log('------afterpermission-------', permissionStore);
  //       permissionStore.initRoutes(ctx.store.roles);
  //     }
  //   },
  // },
});

export function getUserStore() {
  return useUserStore(store);
}
